//路由鉴权:鉴权,项目当中路由能不能被的权限的设置(某一个路由什么条件下可以访问、什么条件不可以访问）
import router from '@/router';
//创建仓库
import pinia from './store';
//获取用户小仓库的数据
import useUserStore from './store/modules/user';
import useDictStore from '@/store/modules/dict';
//引入全局事件mitt
import $bus from '@/bus';
//引入nextTick，将里面的回调函数延迟下次 DOM 更新循环结束之后执行
import { nextTick } from 'vue';
//引入进度条
import { start, close } from '@/utils/nprogress';

let userStore = useUserStore(pinia);
let dictStore = useDictStore(pinia);
if (!userStore.userInfo.userName && userStore.token) {
    await userStore.getUserInfo();
    await dictStore.getDictList([]);
}
//全局守卫：项目当中任务路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to: any, _from: any, next: any) => {    
    start();    
    //to:你将要访问那个路由
    //from:你从来个路由而来
    // console.log('测试前置守卫发送时间',Date())
    let token = userStore.token;
    if (token) {
        //用户登录成功
        if (to.path == '/login') {
            next({ path: '/' }); //放行
        } else {
            next();
        }
    } else {
        //用户未登录
        if (to.path == '/login') {
            next(); //放行            
        } else {
            next({ path: '/login', query: { redirect: to.path } });
        }
    }    
    //next:路由的放行函数
    // $bus.emit('setRoute', { path: to.path, name: to.meta.title, type: to.meta.type })

})
//全局后置守卫
router.afterEach((to: any, _from: any) => {
    // console.log('测试后置守卫发送时间',Date())
    nextTick(() => {                
        $bus.emit('setRoute', { path: to.path, name: to.meta.title, type: to.meta.type }); 
        close();
    });    
    // $bus.emit('setRoute', { path: to.path, name: to.meta.title, type: to.meta.type })
})